﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using sys.datas.Models;

namespace sys.services.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly sys.datas.Context db = new sys.datas.Context();
        public UsersController()
        {
        }

        [HttpGet]
        public ActionResult<List<User>> Get()
        {
            var users = db.Users
                .OrderBy(b => b.UserCode)
                .ToList();
            return users;
        }

        [HttpGet("{userCode:length(24)}", Name = "GetUser")]
        public ActionResult<User> Get(string userCode)
        {
            var user = db.Users
                .Where(b => b.UserCode.Equals(userCode))
                .FirstOrDefault();
            return user;
        }

        [HttpPost]
        public ActionResult<User> Create(User user)
        {
            db.Users.Add(user);
            db.SaveChanges();

            return CreatedAtRoute("GetUser", new { userCode = user.UserCode.ToString() }, user);
        }

        [HttpPut("{userCode:length(24)}")]
        public IActionResult Update(string userCode, User userIn)
        {
            var user = db.Users
                .Where(b => b.UserCode.Equals(userCode))
                .FirstOrDefault();
            if (user == null)
            {
                return NotFound();
            }

            db.Users.Update(userIn);
            return NoContent();
        }

        [HttpDelete("{userCode:length(24)}")]
        public IActionResult Delete(string userCode)
        {
            var user = db.Users
                .Where(b => b.UserCode.Equals(userCode))
                .FirstOrDefault();
            if (user == null)
            {
                return NotFound();
            }

            db.Users.Remove(user);
            return NoContent();
        }
    }
}
